#!/bin/bash
set -euo pipefail

export ZSH="${ZSH:-$HOME/.oh-my-zsh}"
ZSH_CUSTOM="${ZSH_CUSTOM:-$HOME/.oh-my-zsh/custom}"


echo "=================================================="
echo "  Zsh 安装与配置脚本"
echo "  作者：kukuqi666"
echo "=================================================="
echo ""

# 确保有 ca-certificates
if ! dpkg -l | grep -q '^ii.*ca-certificates'; then
    echo "正在安装 CA 证书..."
    sudo apt-get update -qq && sudo apt-get install -y ca-certificates
fi

# 系统更新 & 装软件
sudo apt update && sudo apt upgrade -y
sudo apt install -y zsh git curl wget neofetch

# 改默认 shell（容器里可能失败，忽略）
chsh -s /bin/zsh || true

# >>> ① 优先用官方安装脚本（Gitee 镜像） <<<
if [[ ! -d "$ZSH" ]]; then
    echo ">>> 尝试下载官方安装脚本（Gitee 镜像）..."
    INSTALL_URL="https://gitee.com/kukuqi666/ohmyzsh/raw/master/tools/install.sh"
    # 先拉取脚本；如果失败就退回手动克隆
    if curl -fsSL "$INSTALL_URL" -o /tmp/omz-install.sh; then
        # 给脚本加可执行权并运行（--unattended 跳过交互）
        chmod +x /tmp/omz-install.sh
        sh /tmp/omz-install.sh --unattended
        rm -f /tmp/omz-install.sh
    else
        echo ">>> 下载脚本失败，改用 git 手动克隆..."
        git clone --depth=1 https://gitee.com/kukuqi666/ohmyzsh.git "$ZSH"
        cp "$ZSH/templates/zshrc.zsh-template" "$HOME/.zshrc"
    fi
else
    echo "Oh My Zsh 已存在，跳过克隆..."
fi

# 插件安装（已装跳过）
for repo in zsh-autosuggestions zsh-syntax-highlighting; do
    if [[ ! -d "$ZSH_CUSTOM/plugins/$repo" ]]; then
        echo "正在安装 $repo ..."
        git clone --depth=1 "https://gitee.com/kukuqi666/$repo" "$ZSH_CUSTOM/plugins/$repo"
    fi
done

cat > ~/.zshrc <<'EOF'
# ===== Oh My Zsh =====
export ZSH="$HOME/.oh-my-zsh"
ZSH_THEME="gnzh"
plugins=(git zsh-autosuggestions zsh-syntax-highlighting extract web-search docker kubectl)
source $ZSH/oh-my-zsh.sh

# ===== 系统 =====
# export LANG=en_US.UTF-8
export PATH="$HOME/bin:$HOME/.local/bin:/usr/local/bin:$PATH"

# ===== 历史 =====
HISTSIZE=10000
SAVEHIST=10000
HISTFILE="$HOME/.zsh_history"
setopt SHARE_HISTORY HIST_IGNORE_DUPS HIST_IGNORE_SPACE

# ===== 补全 =====
autoload -Uz compinit && compinit
zstyle ':completion:*' matcher-list 'm:{a-z}={A-Z}'
zstyle ':completion:*' list-colors "${(s.:.)LS_COLORS}"
zstyle ':completion:*' menu select

# ===== 颜色 =====
export LS_COLORS='di=1;34:ln=1;36:so=1;35:pi=1;33:ex=1;32:*.tar=31'
export LESS='-R -i -w'

# ===== 别名 =====
alias ll='ls -alFh --color=auto'
alias la='ls -A --color=auto'
alias l='ls -CF --color=auto'
alias grep='grep --color=auto'
alias cp='cp -iv'
alias mv='mv -iv'
alias rm='rm -iv'
alias mkdir='mkdir -pv'
alias reload='source ~/.zshrc'
alias zshconfig="nano ~/.zshrc"

# ===== 欢迎 =====
neofetch
EOF


echo ""
echo "=================================================="
echo " Zsh 安装与配置完成！"
echo " 执行："zsh" 即可进入带 oh-my-zsh 的新 shell。"
echo " 执行 "echo $SHELL"查看zsh是否为默认shell
echo " 如果不是请执行"chsh -s /bin/zsh" 再执行"source .zshrc"
echo " 后续修改请编辑 ~/.zshrc"
echo " 参考教程：https://kukuqi.netlify.app/2025/10/26/zsh-an-zhuang-yu-pei-zhi/ "
echo "=================================================="